package com.easytopit.demo.spring.mvc.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.easytopit.demo.spring.mvc.domain.JSONResult;
import com.easytopit.demo.spring.mvc.domain.User;

@RestController//Restful
@RequestMapping("/usr")
public class JSONController {

	@GetMapping("/get")
	public User get() {// 发送:User -> JSON -> 序列化
		User user = new User();
		user.setId(1);
		user.setName("ok");
		return user;
	}

	@PostMapping("/add") // 接收: JSON -> User -> 反序列化
	public JSONResult add(@RequestBody User user) {
		return new JSONResult(1, user);
	}
	
	public static void main(String[] args) {
		// 手工使用
		// User -> JSON
		User user = new User();
		user.setId(1);
		user.setName("ok");
		Object json = JSON.toJSON(user);
		System.out.println("User -> JSON:" + json);
		
		// JSON -> User
		User parseObject = JSON.parseObject("{'name':'ok','id':1}", User.class);
		System.out.println("JSON -> User:"+parseObject);
	}

}
